package cn.tyoui.core;

import cn.tyoui.httpclient.HttpCrawler;

/**
 * 线程类
 *
 * @author tyoui
 * @version 1.8.5
 */
public class Crawler implements Runnable {

    private int start, end;
    private HttpCrawler httpCrawler;

    //启动自定义爬虫初始化
    public void init_one() {
        httpCrawler = new HttpCrawler();
    }

    private void setThread(int start, int end) {
        this.start = start;
        this.end = end;
    }


    /**
     * 启动线程
     */
    @Override
    public void run() {
        ControllerCrawler controllerCrawler = new ControllerCrawler();
        try {
            controllerCrawler.setThread(start, end);
            controllerCrawler.start();
            controllerCrawler.initCrawler();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 开始启动多线程
     *
     * @throws Exception 启动失败
     */
    public void start() throws Exception {
        ControllerCrawler controllerCrawler = new ControllerCrawler();
        controllerCrawler.setThread(1, 2);
        controllerCrawler.start();
        int start = Integer.parseInt(controllerCrawler.changer("startIndex", "" + 0));
        int end = Integer.parseInt(controllerCrawler.changer("endIndex", "" + 0));
        int threadNum = Integer.parseInt(controllerCrawler.changer("ThreadNum", "" + 1));
        int loop = (end - start) / threadNum;
        for (int i = 0; i < threadNum; i++) {
            Crawler crawlerThread = new Crawler();
            crawlerThread.setThread(start + i * loop, start + loop * (i + 1));
            Thread thread = new Thread(crawlerThread);
            thread.start();
            System.out.println("这是第" + (i + 1) + "个线程启动");
        }
    }


    public void oneURL(String dir, String url) {
        httpCrawler.setDir(dir);
        try {
            httpCrawler.startCrawler(url, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
